package com.cs.rabbittest.demo.publish;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException;

public class Consumer02_subscribe_sms {
    /**
     * 处理邮件队列
     */
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    /**
     * 关于邮件队列绑定的交换机
     */
    private static final String EXCHANGE_FANOUT_INFORM = "exchange_fanout_inform";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        // create connection
        Connection connection = factory.newConnection();
        // 创建与交换机的通道, 每个通道代表一个会话
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.FANOUT);

        // 声明
        channel.queueDeclare(QUEUE_INFORM_SMS, true, false, false, null);
        // 交换机和绑定队列
        channel.queueBind(QUEUE_INFORM_SMS, EXCHANGE_FANOUT_INFORM, "");
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumer, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException {
                long deliverTag = envelope.getDeliveryTag();
                String exchange = envelope.getExchange();
                // 消息内容
                String message = new String(body, "utf-8");
                System.out.printf("sms消费者收到信息%s\n",message);
            }
        };
        channel.basicConsume(QUEUE_INFORM_SMS,true,consumer);

    }
}
